package vn.edu.ptithcm.pim.validator;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import vn.edu.ptithcm.pim.dom.Task;
import vn.edu.ptithcm.pim.util.DateTimeUtil;

public class UpdateTaskValidator implements Validator {

	Logger log = Logger.getLogger(UpdateTaskValidator.class);

	public boolean supports(@SuppressWarnings("rawtypes") Class clazz) {
		return Task.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) {
		Task task = (Task) target;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "summary",
				"warning.required.task.summary");

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description",
				"warning.required.task.description");

		if (task.getTaskCategory().getCategoryid().intValue() == 0) {
			errors.rejectValue("taskCategory", "warning.required.task.category");
		}

		if (task.getTaskSeverity().getSeverityid().intValue() == 0) {
			errors.rejectValue("taskSeverity", "warning.required.task.severity");
		}

		if (task.getTaskPriority().getPriorityid().intValue() == 0) {
			errors.rejectValue("taskPriority", "warning.required.task.priority");
		}

		if (task.getTaskStatus().getStatusid().intValue() == 0) {
			errors.rejectValue("taskStatus", "warning.invalid.task.status");
		}

		if (!task.getAssignedto().isEmpty()) {
			if (task.getTaskStatus().getStatusid().intValue() == 1) {
				errors.rejectValue("taskStatus", "warning.invalid.task.status");
			}
		} else {
			if (task.getTaskStatus().getStatusid().intValue() != 1) {
				errors.rejectValue("taskStatus",
						"warning.must.select.assignedto");
			}
		}

		Date now = new Date();
		String format = "yyyyMMdd";
		if (task.getStarttime() == null) {
			errors.rejectValue("starttime", "warning.required.task.starttime");
		}

		if (task.getEndtime() != null) {
			if (task.getStarttime() == null) {
				int c = DateTimeUtil.compare2Days(task.getEndtime(), now,
						format);
				if (c < 0) {
					errors.rejectValue("endtime",
							"warning.invalid.task.endtime");
				}
			} else {
				int c = DateTimeUtil.compare2Days(task.getEndtime(),
						task.getStarttime(), format);
				if (c < 0) {
					errors.rejectValue("endtime",
							"warning.invalid.task.endtime");
				}
			}
		}
	}
}
